<script setup>
import {onMounted, ref, watch} from "vue";
import {Search} from "@element-plus/icons-vue";
import {ElMessageBox} from "element-plus";
import AdminUserDialogFrom from "@/pages/system/adminUser/component/Form.vue"
import {pageList, add, update, detail, bindRoles} from '@/api/system/sysUser.js'
import {allTree as orgAllTree} from '@/api/system/organization.js'
import SysRoleSelector from "@/components/system/role-selector.vue";

defineOptions({
  name: '/system/adminUser'
})

//组织部门名称搜索Key
const orgNameSearchKey = ref("")

const sysRoleSelectorVisible = ref(false)
const sysRoleSelectedIds = ref([])

//组织部门Tree集合
const orgData = ref([{
  id: 1,
  name: "琛贝科技",
  children: [
    {id: 2, name: '总经办'},
    {id: 3, name: '财务部'},
    {id: 3, name: '人力资源部'},
    {id: 5, name: '市场营销部'},
    {id: 5, name: '技术研发部'},
  ]
}])

//Tree结构映射配置
const defaultProps = ref({
  children: 'children',
  label: 'name',
})

//组织部门Tree实例
const orgTreeRef = ref([
  {id: 1, name: '琛贝科技'}
])

//搜索对象
const search = ref({
  nickname: "",
  status: "",
  orgId: "",
  pageNum: 1,
  pageSize: 10,
  total: 0
})

//管理员用户集合
const adminUserData = ref([
  {id: 1, username: 'admin', nickname: '超级管理员', sex: 1, phone: 18888888888, email: 'admin@chenbei.com', status: 1, orgId: 1, roleIds: [1], remark: '测试', createTime: '2025-01-01 12:00:00'},
  {id: 2, username: 'admin', nickname: '超级管理员', sex: 1, phone: 18888888888, email: 'admin@chenbei.com', status: 1, orgId: 1, roleIds: [1], remark: '测试', createTime: '2025-01-01 12:00:00'},
  {id: 3, username: 'admin', nickname: '超级管理员', sex: 1, phone: 18888888888, email: 'admin@chenbei.com', status: 1, orgId: 1, roleIds: [1], remark: '测试', createTime: '2025-01-01 12:00:00'},
  {id: 4, username: 'admin', nickname: '超级管理员', sex: 1, phone: 18888888888, email: 'admin@chenbei.com', status: 1, orgId: 1, roleIds: [1], remark: '测试', createTime: '2025-01-01 12:00:00'},
  {id: 5, username: 'admin', nickname: '超级管理员', sex: 1, phone: 18888888888, email: 'admin@chenbei.com', status: 1, orgId: 1, roleIds: [1], remark: '测试', createTime: '2025-01-01 12:00:00'},
])

//管理员用户
const adminUser = ref({
  id: "",
  username: "",
  nickname: "",
  sex: "",
  phone: "",
  email: "",
  status: "",
  orgId: "",
  postId: "",
  roleIds: "",
  remark: "",
  createTime: "",
})

//用户状态枚举
const statusEnum =  ref([
  {label: "启用", value: "1"},
  {label: "禁用", value: "2"},
])

//分页配置
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

//搜索表单实例
const searchFormRef = ref(null)

const adminUserDialogFormVisible = ref(false)
const adminUserDialogFormRef = ref(null)

/**
 * 分页请求
 */
const requestPageList = () => {
  pageList(search.value).then((resp) => {
    adminUserData.value= resp.data.data
    search.value.total = Number.parseInt(resp.data.total)
  })
}

//监听分页点击事件
const handleCurrentChange = (currentPage) => {
  search.value.pageNum = currentPage
  requestPageList()
}

//监听重置
const onReset = () => {
  pagination.value.pageNum = 1
  searchFormRef.value.resetFields()
  search.value.orgId = ''
  requestPageList()
}

//监听搜索事件
const onSearch = () => {
  pagination.value.pageNum = 1
  requestPageList()
}

//处理组织Tree的节点过滤逻辑
const handleOrgTreeFilterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

//监听新增事件
const onAdd = () => {
  adminUserDialogFormVisible.value = true
}

//监听编辑事件
const onEdit = async (rowData) => {
  const resp = await detail(rowData.id)
  adminUser.value = resp.data
  adminUserDialogFormVisible.value = true
}

//监听删除事件
const onDelete = (rowData) => {
  ElMessageBox.confirm('您确定要删除这个用户吗?', '提示', {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(() => {
    console.log(rowData)
  }, () => {})
}

//处理Tree节点点击事件
const handleNodeClick = (value) => {
  search.value.orgId = value.id
  requestPageList()
}

//重置密码
const onResetPassword = (rowData) => {
  ElMessageBox.confirm("确定要重置当前用户的密码吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(() => {
    console.log(rowData)
  }, () => {})
}

//角色授权
const onRoleGrant = (rowData) => {
  detail(rowData.id).then(resp => {
    adminUser.value = rowData
    sysRoleSelectedIds.value = resp.data.roleIds
    sysRoleSelectorVisible.value = true
  })

}

//监听搜索
watch(orgNameSearchKey, (newVal) => {
  orgTreeRef.value.filter(newVal)
})

const handleAdminUserDialogFormConfirm = async (formData) => {
  if (formData.id) {
    await update(formData)
  } else {
    await add(formData)
  }
  requestPageList()
  adminUserDialogFormVisible.value = false
}

//初始化
onMounted(() => {
  requestPageList()

  orgAllTree().then(resp => {
    orgData.value = resp.data
  })
})

//监听角色选择器选择事件
const sysRoleSelectorSelector = async (selected) => {
  if (selected) {
    const selectedRoleIdArr = selected.map(item => (item.id))
    await bindRoles(adminUser.value.id, selectedRoleIdArr)
  }
  sysRoleSelectorVisible.value = false
}
</script>

<template>
<div class="cb-main-container">
  <div class="left cb-common-box">
    <div class="left-box1">
      <el-input v-model="orgNameSearchKey" placeholder="请输入组织部门名称" :prefix-icon="Search" clearable />
    </div>
    <div class="left-box2">
      <el-tree
          default-expand-all
          ref="orgTreeRef"
          :data="orgData"
          :props="defaultProps"
          :filter-node-method="handleOrgTreeFilterNode"
          @node-click="handleNodeClick"
      />
    </div>
  </div>
  <div class="right cb-common-box">
    <div class="search-box" style="margin-bottom: 0">
      <el-form :model="search" ref="searchFormRef" inline>
        <el-form-item label="用户名" prop="nickname">
          <el-input v-model="search.nickname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select style="width: 200px" v-model="search.status" placeholder="请输入用户状态">
            <el-option v-for="(item, index) in statusEnum" :key="index" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="Refresh" @click="onReset">重置</el-button>
          <el-button icon="Search" @click="onSearch" type="primary">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider style="margin: 0"/>
    <div class="main-box">
      <div style="margin-top: 16px">
        <el-button icon="Plus" type="primary" @click="onAdd">新增</el-button>
      </div>
      <el-table class="cb-table-box" empty-text="暂无数据" :data="adminUserData" size="large">
        <el-table-column type="index" label="ID" />
        <el-table-column property="nickname" label="昵称" />
        <el-table-column property="phone" label="手机号" />
        <el-table-column property="organization.name" label="部门" />
        <el-table-column property="post.name" label="岗位" />
        <el-table-column property="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'primary' : 'info'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="right" label="操作" width="240">
          <template #default="scope">
            <el-button type="primary" link @click="onEdit(scope.row)" icon="Edit">编辑</el-button>
            <el-button type="danger" link @click="onDelete(scope.row)" icon="Delete">删除</el-button>
            <el-popover placement="bottom" trigger="click" :width="68">
              <template #reference>
                <el-button type="primary" link icon="DArrowRight">更多</el-button>
              </template>
              <template #default>
                <div style="display: flex; flex-direction: column; justify-content: flex-start">
                  <el-button type="primary" link @click="onResetPassword(scope.row)" icon="Refresh">重置密码</el-button>
                  <el-button type="primary" link @click="onRoleGrant(scope.row)" icon="Lock" style="margin-left: 0">授权角色</el-button>
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next" :total="search.total" :current-page="search.pageNum" style="margin-top: 16px" @current-change="handleCurrentChange" />
    </div>
  </div>

  <!-- 添加/编辑S -->
  <admin-user-dialog-from
      ref="adminUserDialogFormRef"
      v-model:visible="adminUserDialogFormVisible"
      :data="adminUser"
      @confirm="handleAdminUserDialogFormConfirm"></admin-user-dialog-from>
  <!-- 添加/编辑E -->

  <!-- 授权角色S -->
  <sys-role-selector
      v-model:visible="sysRoleSelectorVisible"
      @select="sysRoleSelectorSelector"
      :selected-ids="sysRoleSelectedIds" />
  <!-- 授权角色E -->
</div>
</template>

<style scoped lang="scss">
.cb-main-container {

  .left {
    width: 210px;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    border-right: none;

    .left-box1 {
      margin-bottom: 8px;
    }
  }
  .right {
    flex-grow: 1;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    border-left: none;
  }
}
</style>
